<#assign ctx=request.contextPath />
<#import '${ctx}/sys/include/head.html' as d />
<#import '${ctx}/sys/include/body.html' as c />
<#import '${ctx}/sys/include/table/select.html' as select />
<!DOCTYPE html>
<html>
<head>
    <@d.head title="chart" />
    <!--<script src="${ctx}/resource/echart/echarts.js/" type="text/javascript"></script>-->
    <!--<script src="${ctx}/resource/echart/theme/macarons.js"></script>-->
    <script src="${ctx}/resource/antv/g2.js"></script>
    <script src="${ctx}/resource/antv/dataset.js"></script>
    <style>
        ::-webkit-scrollbar {
            display: none;
        }

        html, body {
            overflow: hidden;
            height: 100%;
            margin: 0;
        }
    </style>
</head>
<@c.body>
<div id="hidenGroup">
    <input type="hidden" value="${chartId!''}" name="chartId"/>
    <input type="hidden" value="${chartName!''}" name="chartName"/>
    <input type="hidden" value="${chartDsId!''}" name="chartDsId"/>
    <input type="hidden" value="${chartDsName!''}" name="chartDsName"/>
    <input type="hidden" value="${chartMetrics!''}" name="chartMetrics"/>
    <input type="hidden" value="${chartDimensions!''}" name="chartDimensions"/>
    <input type="hidden" value="${chartQuerys!''}" name="chartQuerys"/>
    <input type="hidden" value="${chartCustoms!''}" name="chartCustoms"/>
</div>
<div class="layui-tab layui-tab-brief" lay-filter="graph_config">
    <ul class="layui-tab-title">
        <li class="layui-col-md1">图表展示</li>
        <li class="layui-col-md1 layui-this">图表设置</li>
        <div>
            <div class="layui-col-md2 layui-col-md-offset7">
                <button id="table_name" style="margin-left: 11px" class="layui-btn-primary layui-btn-sm">
                    图表名称：${chartName!'未命名图表'}
                </button>
            </div>
        </div>
        <div class="layui-col-md1">
            <button id="save_table" style="margin-left:30%;" class="layui-btn layui-btn-sm">
                保存图表
            </button>
        </div>

    </ul>
    <div class="layui-tab-content">
        <div class="layui-tab-item">
            <div class="layui-form">
                <label>数据过滤条件： </label>
                <a id="add_query_btn" class="layui-btn layui-btn-sm layui-btn-primary layui-btn-radius">
                    增加条件
                </a>

            </div>
            <div id="pic" class="text-center"></div>
            <div class="layui-form" style="text-align: center;">
                <div class="layui-form-item" name="grains">
                    <input type="radio" title="1"/>
                    <input type="radio" title="2"/>
                    <input type="radio" title="3"/>
                </div>
                <input type="hidden" value="root" name="grain_path" value="root"/>
            </div>
        </div>
        <div class="layui-tab-item layui-show">
            <div class="layui-container" style="margin-top: 12px;">
                <div class="layui-row">
                    <form class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">选择数据源</label>
                            <div class="layui-input-block"><@select.table name="dsId"
                                show="dsName" url="${ctx}/biz/c/p/ds-select-table" />
                            </div>
                        </div>
                        <label>指标设置</label>
                        <hr/>
                        <div name="metric_cards">
                            <div class="layui-card" name="metric_card">
                                <div class="layui-card-header">分析指标</div>
                                <div class="layui-card-body">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">计算方式</label>
                                        <div class="layui-input-block">
                                            <select name="aggregation" lay-verify="required"
                                                    lay-filter="metrics_select">
                                                <option value="_count">统计</option>
                                                <option value="count">统计某字段</option>
                                                <option value="sum">累和</option>
                                                <option value="avg">平均值</option>
                                                <option value="unique">唯一值</option>
                                            </select> <input name="metric_type" type="hidden" value="_count"/>
                                        </div>
                                    </div>
                                    <div class="layui-form-item layui-hide">
                                        <label class="layui-form-label">计算字段</label>
                                        <div class="layui-input-block"><@select.table
                                            name="metrics" show="metricsName" title="alias"
                                            url="${ctx}/biz/c/p/field-select-table" />
                                        </div>
                                    </div>
                                    <div name="btn_group" class="" style="float: right">
                                        <a name="add_metric" class="layui-btn layui-btn-primary layui-btn-sm">
                                            <i class="layui-icon">&#xe654;</i>
                                        </a>
                                        <a name="del_metric" class="layui-btn layui-btn-primary layui-btn-sm">
                                            <i class="layui-icon">&#xe640;</i>
                                        </a>
                                    </div>
                                    <div class="layui-clear"></div>
                                </div>
                            </div>
                        </div>
                        <label>维度设置</label>
                        <hr/>
                        <div name="aggregation_cards">
                            <div class="layui-card" name="aggregation_card">
                                <div class="layui-card-header">拆分维度</div>
                                <div class="layui-card-body">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">拆分方式</label>
                                        <div class="layui-input-block">
                                            <select name="aggregation" lay-verify="required"
                                                    lay-filter="aggs_select">
                                                <option value="terms">按字段值</option>
                                                <option value="date">按时间</option>
                                                <option value="range">按区间</option>
                                                <option value="filter">按条件</option>
                                            </select> <input name="aggregation_type" type="hidden" value="terms"/>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">聚合字段</label>
                                        <div class="layui-input-block"><@select.table name="aggs"
                                            title="alias" show="aggsName"
                                            url="${ctx}/biz/c/p/field-select-table" />
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">聚合个数</label>
                                        <div class="layui-input-block">
                                        	<input name="aggs_size" type="text" class="layui-input" value="10"/>
                                        </div>
                                    </div>
                                    <div name="btn_group" class="" style="float: right">
                                        <a name="add_aggregation" class="layui-btn layui-btn-primary layui-btn-sm">
                                            <i class="layui-icon">&#xe654;</i>
                                        </a>
                                        <a name="del_aggregation" class="layui-btn layui-btn-primary layui-btn-sm">
                                            <i class="layui-icon">&#xe640;</i>
                                        </a>
                                    </div>
                                    <div class="layui-clear"></div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</@c.body>
<script type="text/javascript">
    layui.use(['form', 'element', 'appJs', 'layer'], function () {
        var $ = layui.$;
        var form = layui.form, element = layui.element, app = layui.appJs, layer = layui.layer;

        var redraw = true;
        var aggregationsArray = [];
        var metricsArray = [];
        var target_dimension;

        var chart_op = {};

        element.on('tab(graph_config)', function (data) {
            if (data.index == 0) {
                if (redraw) {
                    try {
                        var req = buildRequest();
                        draw(req);
                    } catch (err) {
                        layer.msg("图表设置有误")
                    }
                }
            }
        });

        bindMetricButton();
        bindAggregationButton();
        bindaddqueryButton();
        bindqueryDivEvent();

        function bindMetricButton() {
            $('[name="metric_cards"]').find('[name="btn_group"]:first').find('a[name="del_metric"]').hide();
            $('[name="metric_cards"]').find('a[name="add_metric"]').bind('click', function () {
                var lastCard = $(this).parent().parent().parent();
                var newCard = lastCard.clone(true);
                newCard.find('input[name="metricsName"]').val("");
                newCard.find('input[name="metrics"]').val("");
                newCard.find('input[name="metricsName"]').parent().parent().parent().addClass('layui-hide');
                lastCard.after(newCard);
                $('[name="metric_cards"]').find('[name="btn_group"]').find('a[name="add_metric"]').hide();
                $('[name="metric_cards"]').find('[name="btn_group"]:last').find('a[name="add_metric"]').show();
                $('[name="metric_cards"]').find('[name="btn_group"]').find('a[name="del_metric"]').show();
                $('[name="metric_cards"]').find('[name="btn_group"]:first').find('a[name="del_metric"]').hide();
                form.render();
            });
            $('a[name="del_metric"]').bind('click', function () {
                $(this).parent().parent().parent().remove();
                $('[name="metric_cards"]').find('[name="btn_group"]:last').find('a[name="add_metric"]').show();
            });
        }

        function bindAggregationButton() {
            $('[name="aggregation_cards"]').find('[name="btn_group"]:first').find('a[name="del_aggregation"]').hide();
            $('a[name="add_aggregation"]').bind('click', function () {
                var lastCard = $(this).parent().parent().parent();
                var newCard = lastCard.clone(true);
                newCard.find('input[name="aggsName"]').val("");
                newCard.find('input[name="aggs"]').val("");
                lastCard.after(newCard);
                $('[name="aggregation_cards"]').find('[name="btn_group"]').find('a[name="add_aggregation"]').hide();
                $('[name="aggregation_cards"]').find('[name="btn_group"]:last').find('a[name="add_aggregation"]').show();
                $('[name="aggregation_cards"]').find('[name="btn_group"]').find('a[name="del_aggregation"]').show();
                $('[name="aggregation_cards"]').find('[name="btn_group"]:first').find('a[name="del_aggregation"]').hide();
                form.render();
            });
            $('a[name="del_aggregation"]').bind('click', function () {
                $(this).parent().parent().parent().remove();
                $('[name="aggregation_cards"]').find('[name="btn_group"]:last').find('a[name="add_aggregation"]').show();
            });
        }

        function bindaddqueryButton() {
            $("#add_query_btn").bind('click', function () {
                var $ele = $(this);

                layer.open({
                    type: 2,
                    title: '请选择',
                    maxmin: true,
                    offset: '100px',
                    content: ['${ctx}/biz/c/p/query-input', 'no'],
                    area: ['70%', '267px'],
                    scrollbar: false,
                    success: function (layero, index) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];

                        $(iframeWin.document).find('#check_btn').bind('click', function () {
                            var index = layer.getFrameIndex(iframeWin.name);

                            var fieldId = $(iframeWin.document).find('input[name="query_field_id"]').val();
                            var field = $(iframeWin.document).find('input[name="query_field_name"]').val();
                            var operator = $(iframeWin.document).find('input[name="query_operator"]').val();
                            var val = $(iframeWin.document).find('input[name="query_value"]').val();

                            //add query
                            var $queryDiv = $('<div name="query_div" class="layui-btn layui-btn-sm layui-btn-primary layui-btn-radius"></div>');
                            $fieldSpan = $('<span name="field_name">' + field + '</span>');
                            $queryDiv.append($fieldSpan);
                            $operatorSpan = $('<span name="operator">' + operator + '</span>');
                            $queryDiv.append($operatorSpan);
                            $valSpan = $('<span name="field_val">' + val + '</span>');
                            $queryDiv.append($valSpan);
                            $fieldIdSpan = $('<span name="field_id" class="layui-hide">' + fieldId + '</span>');
                            $queryDiv.append($fieldIdSpan);
                            $ele.before($queryDiv);

                            bindqueryDivEvent();
                            var req = buildRequest();
                            draw(req);
                            layer.close(index);
                        });

                    }
                });
            });
        }

        function bindqueryDivEvent() {
            $('div[name="query_div"]').unbind('click');
            $('div[name="query_div"]').bind('click', function () {
                var ele = this;
                var $div = $('<div class="layui-btn-group">');
                var $btns = $('<a name="edit_query" class="layui-btn layui-btn-primary">编辑</a>' +
                    '<a name="delete_query" class="layui-btn layui-btn-primary">删除</a>');

                $div.append($btns);
                layer.open({
                    type: 4,
                    content: [$div.html(), ele],
                    shadeClose: true,
                    closeBtn: 0,
                    tips: [3, '#fff'],
                    success: function (layero, index) {
                        $('a[name="delete_query"]').bind('click', function () {
                            $(ele).remove();
                            var req = buildRequest();
                            draw(req);
                            layer.close(index)
                        });
                    }
                })
            });
        }

        form.on('select(aggs_select)', function (data) {
            var ele = data.elem;
            var val = data.value;
            $(ele).parent().find('input[name="aggregation_type"]').val(val);
        });
        form.on('select(metrics_select)', function (data) {
            var ele = data.elem;
            var val = data.value;
            $(ele).parent().find('input[name="metric_type"]').val(val);
            if (val != '_count') {
                $(ele).parent().parent().next().removeClass('layui-hide');
            } else {
                $(ele).parent().parent().next().addClass('layui-hide');
            }
        });
        form.render();
        var chart;
        var ds;

        function draw(req) {
			app.ajax('post','${ctx}/biz/visualize/draw',req,function(data){
				if(data.code != 0) {
					layer.msg(data.code+': '+data.msg);
					return;
				}
	            if (typeof chart != 'undefined') {
	                chart.destroy();
	            }
                chart = new G2.Chart({
                    container: 'pic',
                    forceFit: true,
                    height: window.innerHeight - 250
                });

                console.log(data.values.data);
                chart_op.data = data.values.data;
                if (data.code != 0) {
                    layer.msg(data.code + ": " + data.msg);
                    return;
                }
                chart_op.view = [];
				for(var metric of metricsArray) {
                    var viewDef = {};
                    viewDef.axis = {
                    		field:'field'
                    }
					viewDef.metric = metric;
                    if (metric.aggs == '_count') {
                        viewDef.transform = [];
                        viewDef.transform.push({
                            type: 'map',
                            callback(row) {
								var metric = window._metric;
                                var r = {};
                                r.field = row.field;
                                if (target_dimension.inNested) {
                                    var grainPath = $('input[name="grain_path"]').val();
                                    //
                                    r.count = row[grainPath].count;
                                } else {
                                    if (metric.inNested) {
                                        r.count = row[metric.name].count;
                                    } else {
                                        r.count = row.count;
                                    }
                                }
                                return r;
                            }
                        });
                        viewDef.geom = {};
                        viewDef.geom.type = 'interval';
                        viewDef.geom.position = 'field*count';
                    }
                    if (metric.aggs == 'count') {
                        var orignal = data.values.data;
						viewDef.data = function(viewDef){
							var metric = window._metric;
                        var pd = [];
							var grainPath = $('input[name="grain_path"]').val();
                        for (var i of orignal) {
                            var parent = i.field;
                            if (target_dimension.inNested) {
                                if (metric.inNested) {
                                    if (target_dimension.nestedPath == metric.nestedPath) {
											var field_list = i[grainPath][metric.name].doc;
                                        for (var j of field_list) {
                                            var field = j.field;
                                            var count = j.count;
                                            pd.push({parent: parent, field: field, count: count});
                                        }
                                    } else {
                                        if (target_dimension.nestedPath.indexOf(metric.nestedPath) != -1) {
                                            var field_list = i[metric.nestedPath][metric.name].doc;
                                            for (var j of field_list) {
                                                var field = j.field;
                                                var count = j.count;
                                                pd.push({parent: parent, field: field, count: count});
                                            }
                                        } else {
												var field_list = i[grainPath][metric.name].doc;
                                            //var field_list = i.root[metric.name].doc;
                                            for (var j of field_list) {
                                                var field = j.field;
                                                var count = j.count;
                                                pd.push({parent: parent, field: field, count: count});
                                            }
                                        }
                                    }
                                } else {
                                    var grainPath = $('input[name="grain_path"]').val();
                                    //
										var field_list = i[grainPath][metric.name].doc;
                                    //var field_list = i.root.doc;
                                    for (var j of field_list) {
                                        var field = j.field;
                                        var count = j.count;
                                        pd.push({parent: parent, field: field, count: count});
                                    }
                                }
                            } else {
                                if (metric.inNested) {
                                    var field_list = i[metric.name].doc;
                                    for (var j of field_list) {
                                        var field = j.field;
                                        var count = j.count;
                                        pd.push({parent: parent, field: field, count: count});
                                    }
                                } else {
                                    var field_list = i[metric.name].doc;
                                    for (var j of field_list) {
                                        var field = j.field;
                                        var count = j.count;
                                        pd.push({parent: parent, field: field, count: count});
                                    }
                                }
                            }
                        }
							return pd;
						}
						//viewDef.data = pd;
                        viewDef.transform = [];
                        viewDef.transform.push({
                            type: 'percent',
                            field: 'count',
                            dimension: 'field',
                            groupBy: ['parent'],
                            as: 'percent'
                        });
                        viewDef.transform.push({
                            type: "map",
                            callback(row) {
                                row.percent = (row.percent * 100).toFixed(2) + '%';
                                return row;
                            }
                        });
                        viewDef.geom = {};
                        viewDef.geom.type = 'interval';
                        viewDef.geom.position = 'parent*count';
                        viewDef.geom.color = 'field';

                        viewDef.geom.opacity = 1;
                        viewDef.geom.adjust = [{
                            type: 'dodge',
                            marginRatio: 1 / 32
                        }];

                        viewDef.geom.tooltip = {
                            field: 'field*count*percent',
                            callback: function (f, c, p) {
                                return {value: '<span style="color: #1890ff;">' + f + ' : ' + c + ' ,占比: ' + p + '</span>'}
                            }
                        };
                    }
                    if (metric.aggs == 'avg') {
                        //dv = ds.createView().source(data.values.data);
                        viewDef.transform = [];
                        viewDef.transform.push({
                            type: 'map',
                            callback(row) {
								var metric = window._metric;
                                var r = {};
                                r.field = row.field;
                                if (target_dimension.inNested) {
                                    var grainPath = $('input[name="grain_path"]').val();
                                    if (metric.inNested) {
                                        if (target_dimension.nestedPath.indexOf(metric.nestedPath) != -1) {
                                            r.avg = row[metric.nestedPath][metric.name].AVG;
                                        } else {
                                            r.avg = row[grainPath][metric.name].AVG;
                                        }
                                    } else {
                                        r.avg = row[grainPath][metric.name].AVG;
                                    }
                                } else {
                                    if (metric.inNested) {
                                        r.avg = row[metric.nestedPath][metric.name].AVG;
                                    } else {
                                        r.avg = row[metric.name].AVG;
                                    }
                                }
                                return r;
                            }
                        });
                        viewDef.transform.push({
                            type: 'map',
                            callback(row) {
                                row.avg_p = (row.avg * 100).toFixed(2) + '%';
                                return row;
                            }
                        });
                        viewDef.geom = {};
                        viewDef.geom.type = 'line';
                        viewDef.geom.position = 'field*avg';
                        viewDef.geom.tooltip = 'field*avg_p';
                        //geom = cview.source(dv).line().position('field*'+title);
                        //geom.tooltip('field*avg_p');
                    }
                    if (metric.aggs == 'sum') {
                        //dv = ds.createView().source(data.values.data);
                        viewDef.transform = [];
                        viewDef.transform.push({
                            type: 'map',
                            callback(row) {
								var metric = window._metric;
                                var r = {};
                                r.field = row.field;
                                if (target_dimension.inNested) {
                                    var grainPath = $('input[name="grain_path"]').val();
                                    if (target_dimension.nestedPath.indexOf(metric.nestedPath) != -1) {
                                        r.sum = row[metric.nestedPath][metric.name].SUM;
                                    } else {
                                        r.sum = row[grainPath][metric.name].SUM;
                                    }

                                } else {
                                    if (metric.inNested) {
                                        r.sum = row[metric.nestedPath][metric.name].SUM;
                                    } else {
                                        r.sum = row[metric.name].SUM;
                                    }
                                }
                                return r;
                            }
                        });
                        viewDef.geom = {};
                        viewDef.geom.type = 'line';
                        viewDef.geom.position = 'field*sum';
                    }
                    chart_op.view.push(viewDef);
                }
                chart_op.legend = {
                    position: 'top-center'
                };
                chart_op.event = [];
                chart_op.event.push({
					type:'plotclick',
                    fn: function (ev) {
                        console.log('---->');
						console.log(ev);
						console.log(ev.x);
						var records = chart.getTooltipItems({x: ev.x, y: ev.y});
						console.log(records);
                        const data = ev.data;
                        console.log(data);
                        if (data) {
                            const name = data._origin['field'];
                            console.log(name);
                        }
                    }
                })
                console.log(chart_op);
                app.pic(chart, chart_op);
                chart.render();
            });
        }

        function buildRequest() {
            aggregationsArray.length = 0;
            metricsArray.length = 0;
            var $metricCards = $('div[name="metric_card"]');
            var $aggregationCard = $('div[name="aggregation_card"]')
            var $querys = $('div[name="query_div"]');
            var metrics = [];
            $metricCards.each(function (id, card) {
                var metricObj = {};
                var metric_type = $(card).find('input[name="metric_type"]').val();
                var metric_field = $(card).find('input[name="metrics"]').val();
                if (metric_type == '_count') {
                    metrics.push('count()');
                    metricsArray.push({aggs: '_count'})
                } else {
                    if (typeof metric_type != 'undefined' && typeof metric_field != 'undefined')
                        metrics.push(metric_type + '(' + metric_field + ')');
                    app.async_ajax('get', '${ctx}/biz/data/ds/field/get', {id: metric_field}, function (d) {
                        if (d.code == 0) {
                            var field = d.values.data;
                            field.aggs = metric_type;
                            metricsArray.push(field);
                        }
                    });
                }
            });
            $aggregationCard.each(function (id, card) {
                var aggregation_type = $(card).find('input[name="aggregation_type"]').val();
                var aggregation_field = $(card).find('input[name="aggs"]').val();
                var aggregation_size = $(card).find('input[name="aggs_size"]').val();
                if (typeof aggregation_type != 'undefined' && typeof aggregation_field != 'undefined') {
                    app.async_ajax('get', '${ctx}/biz/data/ds/field/get', {id: aggregation_field}, function (d) {
                        if (d.code == 0) {
                            var field = d.values.data;
                            $('div[name="grains"]').html('');
                            if (field.inNested) {
                                var grain = [];
                                grain.push['root'];
                                $('div[name="grains"]').append($('<input type="radio" lay-filter="dimension_grain" name="dimension_grain" title="根节点" value="root" checked="checked" />'));
                                var path = field.nestedPath;
                                var paths = path.split('.');
                                var rp = '';
                                for (var i = 0; i < paths.length; i++) {
                                    if (i == 0) {
                                        rp = paths[i];
                                    } else {
                                        rp = rp + '.' + paths[i];
                                    }
                                    grain.push(rp);
                                    $('div[name="grains"]').append($('<input type="radio" lay-filter="dimension_grain" name="dimension_grain" title="' + rp + '" value="' + rp + '" />'));
                                }
                            }
                            field.grains = grain;
                            form.render('radio');
                            form.on('radio(dimension_grain)', function (data) {
                                $('input[name="grain_path"]').val(data.value);
                                chart.destroy();
                                chart = new G2.Chart({
                                    container: 'pic',
                                    forceFit: true,
                                    height: window.innerHeight - 250
                                });
                                app.pic(chart, chart_op);
                                chart.render();
                                //待完成
                                //chart.changeData(ds).repaint();
                            });
                            aggregationsArray.push({type: aggregation_type, field: field, size:aggregation_size});
                        }
                    });
                }
            });
            var querys = [];
            $querys.each(function (id, query) {
                var queryPack = {};
                var fieldId = $(query).find('span[name="field_id"]').html();
                var operator = $(query).find('span[name="operator"]').html();
                var fieldVal = $(query).find('span[name="field_val"]').html();
                queryPack.field = fieldId;
                queryPack.operator = operator;
                queryPack.value = fieldVal;
                querys.push(queryPack);
            });

            var metrics_request = metrics.join(',');
            console.log(metrics_request);
            target_dimension = aggregationsArray[0].field;
            var dimension = aggregationsArray[0].type + '(' + aggregationsArray[0].field.id + ')';
            var req = {
                metrics: metrics_request,
                ds_id: $('input[name="dsId"]').val(),
                dimension: dimension,
                dimension_size: aggregationsArray[0].size,
                querys: JSON.stringify(querys)
            };
            return req;
        }

        //save_table info
        $("#save_table").unbind('click');
        $("#save_table").bind('click', function () {
            layer.prompt({title: '保存图表-请输入名称', value: $("input[name='chartName']").val()}, function (value, index) {
                layer.close(index);
                try {
                    saveChart(value);
                } catch (err) {
                    console.log(err);
                    layer.msg('保存失败-图表信息不全');
                }
            });
        });

        //save_table info
        function saveChart(chartName) {
            var chartId = $("input[name='chartId']").val();
            var dsId = $("input[name='dsId']").val();
            var dsName = $("input[name='dsName']").val();
            var metrics = [];
            var $metricCards = $('div[name="metric_card"]');
            var dimensions = [];
            var $aggregationCard = $('div[name="aggregation_card"]');
            var querys = [];
            var $querys = $('div[name="query_div"]');

            if (dsId == null || dsId == "") {
                layer.msg("保存失败-未选择数据源");
                return;
            }
            $metricCards.each(function (id, card) {
                var metric_type = $(card).find('input[name="metric_type"]').val();
                var metric_id = $(card).find('input[name="metrics"]').val();
                var metric_name = $(card).find('input[name="metricsName"]').val();
                metrics.push({
                    metricType: metric_type,
                    metricId: metric_id,
                    metricName: metric_name
                });
            });
            $aggregationCard.each(function (id, card) {
                var dimension_type = $(card).find('input[name="aggregation_type"]').val();
                var dimension_id = $(card).find('input[name="aggs"]').val();
                var dimension_name = $(card).find('input[name="aggsName"]').val();
                dimensions.push({
                    dimensionType: dimension_type,
                    dimensionId: dimension_id,
                    dimensionName: dimension_name
                });
            });
            $querys.each(function (id, query) {
                var queryPack = {};
                var fieldId = $(query).find('span[name="field_id"]').html();
                var fieldName = $(query).find('span[name="field_name"]').html();
                var operator = $(query).find('span[name="operator"]').html();
                var fieldValue = $(query).find('span[name="field_val"]').html();
                queryPack.fieldId = fieldId;
                queryPack.operator = operator;
                queryPack.fieldValue = fieldValue;
                queryPack.fieldName = fieldName;
                querys.push(queryPack);
            });
            if (dimensions[0].dimensionId == null || dimensions[0].dimensionId == "") {
                layer.msg("保存失败-未选择维度设置");
                return;
            }
            var chartSettingData = {
                chartName: chartName,
                chartDsId: dsId,
                chartDsName: dsName,
                chartMetrics: JSON.stringify(metrics),
                chartDimensions: JSON.stringify(dimensions),
                chartQuerys: JSON.stringify(querys),
                chartCustoms: "[]"
            };
            if (chartId == "" || chartId == null || chartId == "undefined") {
                app.ajax('post', '${ctx}/biz/visualize/chart_setting/findByChartName', chartSettingData, function (data) {
                    if (data.code == 0) {
                        app.ajax('post', '${ctx}/biz/visualize/chart_setting/add', chartSettingData, function (data) {
                            if (data.code == 0) {
                                $("#table_name").html("图表名称：" + chartName);
                                layer.msg('保存成功');
                                $("input[name='chartName']").val(chartName);
                            } else {
                                layer.msg(data.code + ": " + data.msg);
                            }
                        });
                    } else {
                        layer.msg(data.code + ": " + data.msg);
                    }
                });
            } else {
                eval("chartSettingData.id=" + chartId);
                if (chartName == $("input[name='chartName']").val()) {
                    app.ajax('post', '${ctx}/biz/visualize/chart_setting/updateChartById', chartSettingData, function (data) {
                        if (data.code == 0) {
                            $("#table_name").html("图表名称：" + chartName);
                            layer.msg('保存成功');
                            $("input[name='chartName']").val(chartName);
                        } else {
                            layer.msg(data.code + ": " + data.msg);
                        }
                    });
                } else {
                    app.ajax('post', '${ctx}/biz/visualize/chart_setting/findByChartName', chartSettingData, function (data) {
                        if (data.code == 0) {
                            app.ajax('post', '${ctx}/biz/visualize/chart_setting/updateChartById', chartSettingData, function (data) {
                                if (data.code == 0) {
                                    $("#table_name").html("图表名称：" + chartName);
                                    layer.msg('保存成功');
                                    $("input[name='chartName']").val(chartName);
                                } else {
                                    layer.msg(data.code + ": " + data.msg);
                                }
                            });
                        } else {
                            layer.msg(data.code + ": " + data.msg);
                        }
                    })
                }
            }
        }

        //showChart
        $(document).ready(function () {
            var chartName = $("input[name='chartName']").val();
            if (chartName == null || chartName == "" || chartName == "undefined") {
                return;
            }
            showChart(chartName)
        });

        function showChart(chartName) {
            var chartDsId = $("input[name='chartDsId']").val();
            var chartDsName = $("input[name='chartDsName']").val();
            var chartMetrics = JSON.parse($("input[name='chartMetrics']").val());
            var chartDimensions = JSON.parse($("input[name='chartDimensions']").val());
            var chartQuerys = JSON.parse($("input[name='chartQuerys']").val());
            var chartCustoms = JSON.parse($("input[name='chartCustoms']").val());

            $("input[name='dsId']").val(chartDsId);
            $("input[name='dsName']").val(chartDsName);

            //show metrics
            var chartMetricsLen = chartMetrics.length;
            $.each(chartMetrics, function (index, value) {
                if (index == 0) {
                    if (value.metricType != "_count") {
                        $('input[name="metricsName"]').parent().parent().parent().removeClass('layui-hide');
                    }
                    $("[name='aggregation'] option[value='" + value.metricType + "']").attr("selected", "true");
                    $('input[name="metricsName"]').val(value.metricName);
                    $('input[name="metric_type"]').val(value.metricType);
                    $('input[name="metrics"]').val(value.metricId);
                } else {
                    var lastCard = $('[name="metric_card"]:last');
                    var newCard = lastCard.clone(true);
                    if (value.metricType != "_count") {
                        newCard.find('input[name="metricsName"]').parent().parent().parent().removeClass('layui-hide');
                    }
                    newCard.find("[name='aggregation'] option[value='" + value.metricType + "']").attr("selected", "true");
                    newCard.find('input[name="metricsName"]').val(value.metricName);
                    newCard.find('input[name="metric_type"]').val(value.metricType);
                    newCard.find('input[name="metrics"]').val(value.metricId);
                    lastCard.after(newCard);
                }
            });
            $('[name="metric_cards"]').find('[name="btn_group"]:gt(0)').find('a[name="del_metric"]').show();
            $('[name="metric_cards"]').find('[name="btn_group"]:lt(' + (chartMetricsLen - 1) + ')').find('a[name="add_metric"]').hide();
            //show dimensions
            var chartDimensionsLen = chartDimensions.length;
            $.each(chartDimensions, function (index, value) {
                // 如果只有一个维度，只需要填充数据到页面，
                // 如果有2个及以上维度，需要先填充所有数据（隐藏add，添加del），并隐藏第一个维度add和del图标。添加最有一个维度add和del图标。
                if (index == 0) {
                    $("[name='aggregation'] option[value='" + value.dimensionType + "']").attr("selected", "true");
                    $('input[name="aggsName"]').val(value.dimensionName);
                    $('input[name="aggregation_type"]').val(value.dimensionType);
                    $('input[name="aggs"]').val(value.dimensionId);
                } else {
                    var lastCard = $('[name="aggregation_card"]:last');
                    var newCard = lastCard.clone(true);
                    newCard.find("[name='aggregation'] option[value='" + value.dimensionType + "']").attr("selected", "true");
                    newCard.find('input[name="aggsName"]').val(value.dimensionName);
                    newCard.find('input[name="aggregation_type"]').val(value.dimensionType);
                    newCard.find('input[name="aggs"]').val(value.dimensionId);
                    lastCard.after(newCard);
                }
            });
            $('[name="aggregation_cards"]').find('[name="btn_group"]:gt(0)').find('a[name="del_aggregation"]').show();
            $('[name="aggregation_cards"]').find('[name="btn_group"]:lt(' + (chartDimensionsLen - 1) + ')').find('a[name="add_aggregation"]').hide();
            //show querys
            $.each(chartQuerys, function (index, value) {
                var $ele = $("#add_query_btn");
                var $queryDiv = $('<div name="query_div" class="layui-btn layui-btn-sm layui-btn-primary layui-btn-radius"></div>')
                $fieldSpan = $('<span name="field_name">' + value.fieldName + '</span>');
                $queryDiv.append($fieldSpan);
                $operatorSpan = $('<span name="operator">' + value.operator + '</span>');
                $queryDiv.append($operatorSpan);
                $valSpan = $('<span name="field_val">' + value.fieldValue + '</span>');
                $queryDiv.append($valSpan);
                $fieldIdSpan = $('<span name="field_id" class="layui-hide">' + value.fieldId + '</span>');
                $queryDiv.append($fieldIdSpan);
                $ele.before($queryDiv);
                bindqueryDivEvent();
                console.log($ele);
            });
            form.render();
        }
    });
</script>